package com.jack.network;

import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.jack.network.utils.Constants;
import com.jack.network.utils.NetworkUtils;

/**
 * 网络状态监听工具， Android 21 以上可用
 * */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {

    private NetWorkType netType;

    private NetWorkMonitorImpl mNetWorkMonitorImpl;

    public NetworkCallbackImpl() {
        netType = NetWorkType.NONE;
    }

    public void setNetWorkMonitor(INetWorkMonitor monitor) {
        mNetWorkMonitorImpl = (NetWorkMonitorImpl) monitor;
    }

    @Override
    public void onAvailable(@NonNull Network network) {
        super.onAvailable(network);
        Log.d(Constants.TAG, "[NetworkCallbackImpl] 网络连接");
    }

    @Override
    public void onLost(@NonNull Network network) {
        super.onLost(network);
        Log.d(Constants.TAG, "[NetworkCallbackImpl] 网络中断");
    }

    @Override
    public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities);
        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                Log.d(Constants.TAG, "[NetworkCallbackImpl] 网络发生变更，类型为 wifi");
            } else {
                Log.d(Constants.TAG, "[NetworkCallbackImpl] 网络发生变更，类型为其他");
            }

            netType = NetworkUtils.getNetType(NetworkManager.getDefault().getApplication());

            mNetWorkMonitorImpl.notifyNetwork(netType);
        }
    }

}
